<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="能量球名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入能量球名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="等级" prop="grade">
            <el-select v-model="form.grade" placeholder="请选择">
              <el-option
                v-for="item in optionsgrade"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="达到多少亏损值触发" prop="num1">
            <el-input type="number" style="width: 200px;" placeholder="请输入" v-model="form.val">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="获得触发概率" prop="probability">
            <el-input
              type="number"
              style="width: 200px;"
              placeholder="请输入获得触发概率"
              v-model="form.probability"
            >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="王者款获奖概率" prop="num1">
            <el-input type="number" style="width: 200px;" placeholder="请输入获奖概率" v-model="form.hero">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col v-for="(item,index) in form.data" :key="index" :span="8">
          <el-form-item style="width: 100%;" :label="`(${item.label})获奖概率`">
            <el-input type="number" style="width: 200px;" placeholder="请输入获奖概率" v-model="item.val">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="上传图标" prop="icon">
            <span style="color:red">建议尺寸128*128</span>
            <el-upload
              class="avatar-uploader"
              action="https://upload-z0.qiniup.com/"
              :data="postData"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="背景图" prop="bg_img">
            <span style="color:red">建议尺寸490*420</span>
            <el-upload
              class="avatar-uploader"
              action="https://upload-z0.qiniup.com/"
              :data="postData"
              :show-file-list="false"
              :on-success="handleAvatarSuccessbg"
              :before-upload="beforeAvatarUploadbg"
            >
              <img v-if="form.bg_img" :src="form.bg_img" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-button
            size="small"
            style="margin-bottom: 10px;"
            type="primary"
            round
            @click="addRewards(4)"
          >添加普通奖品</el-button>
          <el-table
            :header-cell-style="{background:'#eee'}"
            :data="form.blindsData4"
            border
            style="width: 100%;margin-bottom: 20px;"
          >
            <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
            <el-table-column align="center" label="图片" width="70">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.img" alt style="max-width:60px" />
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.img"
                  ></el-avatar>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-popconfirm
                  confirmButtonText="好的"
                  cancelButtonText="不用了"
                  icon="el-icon-info"
                  iconColor="red"
                  title="这是一段内容确定删除吗？"
                  @onConfirm="handleDel4(scope.row)"
                >
                  <el-button slot="reference" type="text" size="small" style="color:red">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <el-button
            size="small"
            style="margin-bottom: 10px;"
            type="warning"
            round
            @click="addRewards(3)"
          >添加稀有奖品</el-button>
          <el-table
            :header-cell-style="{background:'#eee'}"
            :data="form.blindsData3"
            border
            style="width: 100%;margin-bottom: 20px;"
          >
            <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
            <el-table-column align="center" label="图片" width="70">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.img" alt style="max-width:60px" />
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.img"
                  ></el-avatar>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-popconfirm
                  confirmButtonText="好的"
                  cancelButtonText="不用了"
                  icon="el-icon-info"
                  iconColor="red"
                  title="这是一段内容确定删除吗？"
                  @onConfirm="handleDel3(scope.row)"
                >
                  <el-button slot="reference" type="text" size="small" style="color:red">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <el-button
            size="small"
            style="margin-bottom: 10px;"
            type="danger"
            round
            @click="addRewards(2)"
          >添加史诗奖品</el-button>
          <el-table
            :header-cell-style="{background:'#eee'}"
            :data="form.blindsData2"
            border
            style="width: 100%;margin-bottom: 20px;"
          >
            <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
            <el-table-column align="center" label="图片" width="70">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.img" alt style="max-width:60px" />
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.img"
                  ></el-avatar>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-popconfirm
                  confirmButtonText="好的"
                  cancelButtonText="不用了"
                  icon="el-icon-info"
                  iconColor="red"
                  title="这是一段内容确定删除吗？"
                  @onConfirm="handleDel2(scope.row)"
                >
                  <el-button slot="reference" type="text" size="small" style="color:red">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="toBack()">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 抽屉 -->
    <el-dialog title="提示" :visible.sync="drawer" width="80%" :before-close="handleClose">
      <div>
        <FormTable @drawerClose="drawerClose" v-if="drawer"></FormTable>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { boxRewardList, boxRewardTypeList } from '@/api/boxreward'
import {
  energyList,
  addEnergy,
  editEnergy,
  energyDetails,
  delEnergy
} from '@/api/energy'
import { rewardList } from '@/api/system'
import { parseTime } from '@/utils/index'
import FormTable from './formtable.vue'
import { upload } from '@/api/system'

export default {
  name: 'AddBoxWX',
  components: {
    FormTable
  },
  props: {
    dataId: {
      type: String,
      default: ''
    }
  },
  watch: {
    dataId: {
      handler(newVal, oldVal) {
        console.log(newVal + '新的', oldVal + '旧的')
        if (newVal) {
          this.dataId = newVal
          this.getDetails()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getToken()
  },
  data() {
    return {
      formLoading: false,
      // 等级
      optionsgrade: [
        {
          value: '1',
          label: '等级1'
        },
        {
          value: '2',
          label: '等级2'
        },
        {
          value: '3',
          label: '等级3'
        },
        {
          value: '4',
          label: '等级4'
        },
        {
          value: '5',
          label: '等级5'
        }
      ],
      boxRewardData: [],
      form: {
        name: '',
        hero: null,
        val: null,
        probability: null,
        icon: '',
        bg_img: '',
        grade: '',
        blindsData4: [],
        blindsData3: [],
        blindsData2: [],
        data: [
          { key: '1', label: '普通', val: null },
          { key: '2', label: '稀有', val: null },
          { key: '3', label: '史诗', val: null }
        ]
      },
      rules: {
        name: [{ required: true, message: '请输入盲盒名称', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传封面图片', trigger: 'blur' }],
        details_img: [
          { required: true, message: '请上传详情图片', trigger: 'blur' }
        ],
        class_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        price: [{ required: true, message: '请输入奖单价', trigger: 'blur' }],
        extract_ci: [
          { required: true, message: '请输入单箱抽取次数', trigger: 'blur' }
        ],
        is_ls: [{ required: true, message: '请输入流水限制', trigger: 'blur' }],
        pattern: [
          { required: true, message: '请选择抽取方式', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        is_tui: [
          { required: true, message: '请选择是否推荐', trigger: 'blur' }
        ],
        is_cc: [
          { required: true, message: '请选择是否存在冲冲赏', trigger: 'blur' }
        ],
        is_integral: [
          { required: true, message: '请输选择是否产生积分', trigger: 'blur' }
        ],
        integral: [
          { required: true, message: '请输入积分数量', trigger: 'blur' }
        ],
        goods_data: [{ required: true, message: '请选择奖品', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      // imageUrl: '',
      // bg_imgUrl: '',
      postData: {
        token: ''
      },
      detailUrl: '',
      // 编辑抽屉
      drawer: false,
      rewardNum: ''
    }
  },
  mounted() {},
  activated() {},
  methods: {
    handleDel4(item) {
      this.form.blindsData4 = this.form.blindsData4.filter(
        (i) => i.goods_id != item.goods_id
      )
      console.log(this.form.blindsData4)
      this.$forceUpdate()
    },
    handleDel3(item) {
      this.form.blindsData3 = this.form.blindsData3.filter(
        (i) => i.goods_id != item.goods_id
      )
      this.$forceUpdate()
    },
    handleDel2(item) {
      this.form.blindsData2 = this.form.blindsData2.filter(
        (i) => i.goods_id != item.goods_id
      )
      this.$forceUpdate()
    },
    getDetails() {
      if (this.dataId) {
        energyDetails({ id: this.dataId }).then((res) => {
          this.form = res.data
          this.form.blindsData4 = res.data.goods_grade1
          this.form.blindsData3 = res.data.goods_grade2
          this.form.blindsData2 = res.data.goods_grade3
        })
      }
    },
    drawerClose(arr) {
      this.drawer = false
      if (this.rewardNum == '4') {
        this.form.blindsData4 = this.uniqueArrayObjects(
          this.form.blindsData4.concat(
            arr.map((res) => {
              return Object.assign(res, {
                goods_id: res.id
              })
            })
          )
        )
      }
      if (this.rewardNum == '3') {
        this.form.blindsData3 = this.uniqueArrayObjects(
          this.form.blindsData3.concat(
            arr.map((res) => {
              return Object.assign(res, {
                goods_id: res.id
              })
            })
          )
        )
      }
      if (this.rewardNum == '2') {
        this.form.blindsData2 = this.uniqueArrayObjects(
          this.form.blindsData2.concat(
            arr.map((res) => {
              return Object.assign(res, {
                goods_id: res.id
              })
            })
          )
        )
      }
    },
    uniqueArrayObjects(arr) {
      const unique = []
      const seen = new Set()

      arr.forEach((item) => {
        const itemString = JSON.stringify(item)
        if (!seen.has(itemString)) {
          seen.add(itemString)
          unique.push(item)
        }
      })

      return unique
    },

    onSubmit() {
      console.log(this.form)
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // grade    1普通  2稀有   3史诗   4传说
          // rule_id 34普通  33稀有 32史诗： 31传说（英雄款
          const arr4 = this.form.blindsData4.map((item) => {
            return Object.assign(item, {
              // goods_id: goods_id || item.id,
              rule_id: 34,
              grade: 1
            })
          })
          const arr3 = this.form.blindsData3.map((item) => {
            return Object.assign(item, {
              // goods_id: goods_id || item.id,
              rule_id: 33,
              grade: 2
            })
          })
          const arr2 = this.form.blindsData2.map((item) => {
            return Object.assign(item, {
              // goods_id: goods_id || item.id,
              rule_id: 32,
              grade: 3
            })
          })

          this.form = Object.assign(this.form, {
            goods_data: arr3.concat(arr2).concat(arr4),
            grade: +this.form.grade,
            hero: +this.form.hero,
            val: +this.form.val,
            grade: +this.form.grade
          })
          if (!this.form.id) {
            addEnergy(this.form).then((res) => {
              if (res.st == 1) {
                this.$message.success('添加成功')
                this.$emit('tolist')
              } else {
                this.$message.success(res.msg)
              }
            })
          } else {
            editEnergy(this.form).then((res) => {
              if (res.st == 1) {
                this.$message.success('修改成功')
                this.$emit('tolist')
              } else {
                this.$message.success(res.msg)
              }
            })
          }
        }
      })
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      // this.imageUrl = this.url + res.key
      this.form.icon = this.url + res.key
    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },

    handleAvatarSuccessbg(res, file) {
      // this.bg_imgUrl = this.url + res.key

      this.form.bg_img = this.url + res.key
    },
    beforeAvatarUploadbg(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },
    async getToken() {
      const res = await upload()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },

    handleClose() {
      this.drawer = false
    },

    // 添加奖品
    async addRewards(num) {
      this.drawer = true
      this.rewardNum = num
      // const select = []
      // console.log(this.form.goods_data)
      // if (this.form.goods_data) {
      //   this.form.goods_data.forEach((good) => {
      //     this.boxRewardData.forEach((item) => {
      //       if (good.goods_id == item.id) {
      //         select.push(item)
      //       }
      //     })
      //   })
      // }
      // this.selectArr = this.form.goods_data.map((res) => {
      //   return Object.assign({}, res, {
      //     goods_id: res.id
      //   })
      // })
    },
    toBack() {
      this.$emit('tolist')
    }
  }
}
</script>
<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}

::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 850px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
